package utils

import (
	"fmt"
	"os"
	"time"
)

var protocolMap = map[uint8]string{
	1:  "ICMP",
	6:  "TCP",
	17: "UDP",
	2:  "IGMP",
	89: "OSPF",
	4:  "IP",
	41: "IPv6",
	47: "GRE",
	50: "ESP",
	51: "AH",
}

// FormatIPAddress 将32位整数转换为IP地址字符串
func FormatIPAddress(ip uint32) string {
	return fmt.Sprintf("%d.%d.%d.%d",
		(ip>>24)&0xFF,
		(ip>>16)&0xFF,
		(ip>>8)&0xFF,
		ip&0xFF)
}

// GetProtocolName 获取协议名称
func GetProtocolName(protocol uint8) string {
	if name, exists := protocolMap[protocol]; exists {
		return name
	}
	return fmt.Sprintf("未知协议 (%d)", protocol)
}

// ParseFlags 解析标志位
func ParseFlags(flags uint8) (reserved, dontFragment, moreFragments bool) {
	reserved = (flags & 0x04) != 0
	dontFragment = (flags & 0x02) != 0
	moreFragments = (flags & 0x01) != 0
	return
}

// Logger 日志写入器
type Logger struct {
	file *os.File
}

// NewLogger 创建新的日志写入器
func NewLogger(filename string) (*Logger, error) {
	file, err := os.Create(filename)
	if err != nil {
		return nil, err
	}

	// 写入日志文件头部
	header := fmt.Sprintf("IP数据包解析日志 - 开始时间: %s\n", time.Now().Format("2006-01-02 15:04:05"))
	header += "=========================================\n\n"

	_, err = file.WriteString(header)
	if err != nil {
		file.Close()
		return nil, err
	}

	return &Logger{file: file}, nil
}

// Write 写入日志
func (l *Logger) Write(content string) error {
	_, err := l.file.WriteString(content)
	if err != nil {
		return err
	}
	return l.file.Sync()
}

// Close 关闭日志文件
func (l *Logger) Close() error {
	if l.file != nil {
		// 写入结束信息
		footer := fmt.Sprintf("\n程序结束时间: %s\n", time.Now().Format("2006-01-02 15:04:05"))
		l.file.WriteString(footer)
		return l.file.Close()
	}
	return nil
}
